import 'dart:convert';
import 'dart:io';
import 'dart:isolate';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:xiongan_app_yy/common/user_singleton.dart';
import 'package:xiongan_app_yy/entrys/rp/personl_data_entity.dart';
import 'package:xiongan_app_yy/net/internet_api.dart';
import 'package:xiongan_app_yy/pages/common/LoadBuilder.dart';
import 'package:xiongan_app_yy/utils/eventBus.dart';
import 'package:xiongan_app_yy/utils/image_utils.dart';
import 'package:xiongan_app_yy/utils/toast_utils.dart';
import 'package:xiongan_app_yy/widgets/comm/head_portrait_text_card_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/left_icon_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/text_exhibition_card_widget.dart';

//个人资料
class PersonalDataPage extends StatefulWidget {
  Map<String, dynamic> param;

  PersonalDataPage(this.param);

  @override
  State<StatefulWidget> createState() {
    return PersonalDataPageState();
  }
}

class PersonalDataPageState extends State<PersonalDataPage> {
  String stringText = "无";
  var _futureBuilderFuture;

  String data;

  PersonlDataEntity entity;

  bool load = false;
  Color loadBgColor = Color(0x66BCBCBC);

  Widget _image;
  bool _imageReplace = false;
  String imageUrl;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _futureBuilderFuture = getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
          backgroundColor: Color(0XFF00A5F1),
          automaticallyImplyLeading: false,
          //设置没有返回按钮
          title: Text(
            "个人资料",
            style: TextStyle(fontSize: 18),
          ),
          elevation: 0,
          centerTitle: true,
          leading: LeftIconWidget(icon: Icons.chevron_left, isize: 36),
        ),
        body: LoadBuilder(
          bgColor: loadBgColor,
          visibility: load,
          builder: FutureBuilder(
            builder: _buildFuture,
            future: _futureBuilderFuture,
          ),
        ));
  }

  ///snapshot就是_calculation在时间轴上执行过程的状态快照
  Widget _buildFuture(BuildContext context, AsyncSnapshot snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        print('还没有开始网络请求');
        return Text('还没有开始网络请求');
      case ConnectionState.active:
        print('active');
        return Text('ConnectionState.active');
      case ConnectionState.waiting:
        print('waiting');
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.done:
        print('done');
        if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        }
        return _createListView(context, snapshot);
      default:
        return null;
    }
  }

  Widget _createListView(BuildContext context, AsyncSnapshot snapshot) {
    data = snapshot.data.toString();
    Map<String, dynamic> dataMap = jsonDecode(data);
    entity = PersonlDataEntity.fromJson(dataMap);
    if (imageUrl != null && imageUrl != "") {
      _image = ClipRRect(
        borderRadius: BorderRadius.circular(80),
        child: Image.memory(
          //base64.decode(image),
          base64Decode(imageUrl),
          height: 80,
          width: 80,
          fit: BoxFit.fill,
          gaplessPlayback: true, //防止重绘
        ),
      );
    } else {
      if (entity.descUser.datas.imageurl != null) {
        if (_imageReplace == true) {
          _imageReplace = false;
        } else {
          _image = ImageReplaceCard(entity.descUser.datas.imageurl);
        }
      } else {
        if (_imageReplace == true) {
          _imageReplace = false;
        } else {
          _image = Icon(
            Icons.person,
            size: 25,
            color: Colors.blue,
          );
        }
      }
    }
    return SingleChildScrollView(
      child: Container(
        child: Column(
          children: <Widget>[
            TextExhibitionCardWidget(
                distance:
                    EdgeInsets.only(right: 15, left: 15, bottom: 16, top: 16),
                title: "手机号码",
                exhibitionText: entity.user.datas.useraccount ?? "无"),
            TextExhibitionCardWidget(
                distance:
                    EdgeInsets.only(right: 15, left: 15, bottom: 16, top: 16),
                title: "用户姓名",
                exhibitionText: entity.user.datas.username ?? "无"),
            TextExhibitionCardWidget(
                distance:
                    EdgeInsets.only(right: 15, left: 15, bottom: 16, top: 16),
                title: "角色",
                exhibitionText: entity.user.datas.rolename ?? "无"),
            TextExhibitionCardWidget(
                distance:
                    EdgeInsets.only(right: 15, left: 15, bottom: 16, top: 16),
                title: "部门",
                exhibitionText: entity.user.datas.orgname ?? "无"),
            HeadPortraitTextCardWidget(
                title: "头像",
                iconImage: _image,
                visibility: widget.param["other"],
                onPressed: () {
                  //getImage();
                  if (!widget.param["other"]) {
                    showModalBottomSheet(
                        context: context,
                        builder: (BuildContext context) {
                          return new Column(
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                              new ListTile(
                                leading: new Icon(Icons.photo_camera),
                                title: new Text("相机"),
                                onTap: () {
                                  getCameraImage();
                                  Navigator.pop(context);
                                },
                              ),
                              new ListTile(
                                leading: new Icon(Icons.photo_library),
                                title: new Text("相册"),
                                onTap: () async {
                                  getImage();
                                  Navigator.pop(context);
                                },
                              ),
                            ],
                          );
                        });
                  }
                },
                margin: EdgeInsets.only(top: 10)),
            TextExhibitionCardWidget(
                distance:
                    EdgeInsets.only(right: 15, left: 15, bottom: 16, top: 16),
                title: "工号",
                exhibitionText: entity.user.datas.jobnumber ?? "无"),
            TextExhibitionCardWidget(
                distance:
                    EdgeInsets.only(right: 15, left: 15, bottom: 16, top: 16),
                title: "邮箱",
                exhibitionText: entity.user.datas.email ?? "无"),
            TextExhibitionCardWidget(
                distance:
                    EdgeInsets.only(right: 15, left: 15, bottom: 16, top: 16),
                title: "短号码",
                exhibitionText: entity.user.datas.shortnumber ?? "无"),
            TextExhibitionCardWidget(
                distance:
                    EdgeInsets.only(right: 15, left: 15, bottom: 16, top: 16),
                title: "车牌号",
                exhibitionText: entity.descUser.datas.carno ?? "无"),
            TextExhibitionCardWidget(
                distance:
                    EdgeInsets.only(right: 15, left: 15, bottom: 16, top: 16),
                title: "备注",
                exhibitionText: entity.descUser.datas.note ?? "无"),
          ],
        ),
      ),
    );
  }

  Future getData() async {
    //http://192.168.1.138:5000//aabb10c48844406d98cd6309f9a4bc24
    var response = InternetAPI.getInstance().dio.get(
          "PptUser/${widget.param["id"]}",
        );
    return response;
  }

  Future getImage() async {
    ImagePicker.pickImage(source: ImageSource.gallery).then((image) {
      if (image != null) {
        imageUrl = base64Encode(File(image).readAsBytesSync());
        entity.descUser.datas.imageurl = imageUrl;
        FormData formData = new FormData.from({
          "upload": new UploadFileInfo(
              new File(image), image.substring(image.lastIndexOf("/") + 1)),
        });
        InternetAPI.getInstance().post(
          "FileUpload/File/UploadFlie",
          (data) {
            submitImage(data);
          },
          params: formData,
        );
        setState(() {
          _image = ClipRRect(
            borderRadius: BorderRadius.circular(80),
            child: Image.file(
              new File(image),
              fit: BoxFit.fill,
            ),
          );
          _imageReplace = true;
        });
      }
    });
  }

  getCameraImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    if (image != null) {
      imageUrl = base64Encode(File(image).readAsBytesSync());
      entity.descUser.datas.imageurl = imageUrl;
      setState(() {
        _image = ClipRRect(
          borderRadius: BorderRadius.circular(80),
          child: Image.file(
            new File(image),
            fit: BoxFit.fill,
          ),
        );
        _imageReplace = true;
      });
      upImage(image);
    }
  }

  void upImage(String image) {
    ReceivePort receiverPort = ReceivePort(); //main的isolate的接收端口
    Isolate.spawn(entryPoint, receiverPort.sendPort);
    receiverPort.listen((t) {
      //dart的一个isolate的运行过程，也是通过事件驱动的，通过事件队列的循环，来响应各种变化。
      if (t is SendPort) {
        t.send(image);
      } else {
        print("main接收到 B  发来的消息~~~~~" + t);
        submitImage(t);
      }
    });
  }

  static void entryPoint(SendPort sendPort) {
    //main的sendPort
    ReceivePort receiverPort = new ReceivePort();
    sendPort.send(receiverPort.sendPort); //但是我们要实现双向通信，那就必须，把B的sendPort给main
    receiverPort.listen((t) {
      print("B接收到 main 的消息~~~~~" + t);
      FormData formData = new FormData.from({
        "upload": new UploadFileInfo(
            new File(t), t.substring(t.lastIndexOf("/") + 1)),
      });
      InternetAPI.getInstance().post(
        "FileUpload/File/UploadFlie",
        (data) {
          sendPort.send(data);
        },
        params: formData,
      );
    });
  }

  void submitImage(imgUrl) {
    InternetAPI.getInstance().post(
      "Wconfiguration/DescUser/UpdateDescUser",
      (data) {
        if (data) {
          TostUtil.showToast("修改成功");
          EventBus.getDefault().post(imageUrl);
        }
      },
      params: {
        "imageurl": imgUrl,
        'operaterUserId': DataSingleton().Data.id,
        'operaterUserName': DataSingleton().Data.username,
        'userid': DataSingleton().Data.id,
        'id': entity.descUser.datas.id,
        'isactive': entity.descUser.datas.isactive,
        'isadmin': entity.descUser.datas.isadmin,
        //   'systemtype': DataSingleton().Data.systemtype,
        'issysadmin': entity.descUser.datas.issysadmin,
        'tenantId': DataSingleton().Data.tenantId,
        'warehouseid': DataSingleton().Data.warehouseList[0].id,
      },
      options: Options(
          contentType: ContentType.parse("application/x-www-form-urlencoded")),
    );
  }
}

class ImageReplaceCard extends StatefulWidget {
  final String asetImg;

  ImageReplaceCard(this.asetImg) : assert(asetImg != null);

  @override
  State<StatefulWidget> createState() {
    return ImageReplaceCardState();
  }
}

class ImageReplaceCardState extends State<ImageReplaceCard> {
  String image = "";

  @override
  void initState() {
    print("去下载");
    ImageDownloadUtil.getImageBase64(widget.asetImg, (data) {
      print("下载完成");
      setState(() {
        image = data;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return ClipRRect(
      borderRadius: BorderRadius.circular(80),
      child: Image.memory(
        //base64.decode(image),
        base64Decode(image),
        height: 80,
        width: 80,
        fit: BoxFit.fill,
        gaplessPlayback: true, //防止重绘
      ),
    );
  }
}
